package com.gf.base.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.gf.base.dao.BaseDao;
import com.gf.common.bean.Page;

/**
 * 
 * @author zhuguifeng
 * 
 */
@Repository
public class BaseDaoImpl implements BaseDao {

	@Autowired
	protected HibernateTemplate hibernateTemplate;
	
	
	/**
	 * 根据约束条件，取得分页结果
	 * @param cl
	 * @param criterions:Restrictions
	 * @param page:<font color='red'>必须设置pageSize,total,currentPage三个参数</font>
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected <T> List<T> getPaginationResult(final Class cl,
			final Criterion[] criterions, final Page page) {

		return hibernateTemplate.executeFind(new HibernateCallback<T>() {

			@Override
			public T doInHibernate(Session session) throws HibernateException,
					SQLException {
				Criteria criteria = session.createCriteria(cl);
				for (Criterion criterion : criterions) {
					criteria.add(criterion);
				}
				criteria.setFirstResult(page.getStartIndex());
				criteria.setMaxResults(page.getPageSize());

				return (T) criteria.list();
			}
		});
	}

	/**
	 * 返回一定条件的结果总数<br>
	 * hql参数对应的值以?形式代替
	 * 
	 * @param hql
	 *            :select count(id) from User
	 * @return
	 */
	protected int getTotalResult(String hql, Object... objects) {
		Long count = (Long) hibernateTemplate.find(hql, objects).listIterator()
				.next();
		return Integer.valueOf(count + "");
	}
}
